/*
 * Copyright 2009 XueSong Guo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.webwheel.compiler;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class MyClassLoader extends ClassLoader {

    private Map<String, byte[]> byteCodes = new ConcurrentHashMap<String,byte[]>();

    MyClassLoader(ClassLoader parent) {
        super(parent);
    }

    public Map<String, byte[]> getByteCodes() {
        return Collections.unmodifiableMap(byteCodes);
    }

    public Set<String> getLoadedClasses() {
        return Collections.unmodifiableSet(byteCodes.keySet());
    }

    public byte[] getByteCode(String name) {
        byte[] bytes = byteCodes.get(name);
        if(bytes==null) return null;
        try {
            GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(bytes));
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] buf = new byte[8192];
            int rd;
            while ((rd = gis.read(buf)) != -1) {
                bos.write(buf, 0, rd);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("impossible");
        }
    }

    public Class defineClass(String name, byte[] byteCode) {
        Class<?> cls = defineClass(name, byteCode, 0, byteCode.length);
        resolveClass(cls);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gos = new GZIPOutputStream(bos);
            gos.write(byteCode);
            gos.finish();
            gos.close();
            byteCodes.put(name, bos.toByteArray());
        } catch (IOException e) {
            throw new RuntimeException("impossible");
        }
        return cls;
    }
}
